package lxx.pandams.dao;

import java.util.ArrayList;
import java.util.List;

import lxx.pandams.bean.BlackNumberInfo;
import lxx.pandams.db.CommSafeOpenHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class CommSafeDao {
	
	private CommSafeOpenHelper commSafeOpenHelper;
	//BlackNumberDao单例模式
	//1,私有化构造方法
	private CommSafeDao(Context context){
		//创建数据库已经其表机构
		commSafeOpenHelper = new CommSafeOpenHelper(context);
	}
	//2,声明一个当前类的对象
	private static CommSafeDao commSafeDao = null;
	//3,提供一个静态方法,如果当前类的对象为空,创建一个新的
	public static CommSafeDao getInstance(Context context){
		if(commSafeDao == null){
			commSafeDao = new CommSafeDao(context);
		}
		return commSafeDao;
	}
	
	public void insert(String phone,String mode){
		//1,开启数据库,准备做写入操作
		SQLiteDatabase db = commSafeOpenHelper.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put("phone", phone);
		values.put("mode", mode);
		db.insert("blacknumber", null, values);
		
		db.close();
	}
	
	public void delete(String phone){
		SQLiteDatabase db = commSafeOpenHelper.getWritableDatabase();

		db.delete("blacknumber", "phone = ?", new String[]{phone});
		
		db.close();
	}
	
	public List<BlackNumberInfo> findAll(){
		SQLiteDatabase db = commSafeOpenHelper.getWritableDatabase();

		Cursor cursor = db.query("blacknumber", new String[]{"phone","mode"}, null, null, null, null, "_id desc");
		List<BlackNumberInfo> blackNumberList = new ArrayList<BlackNumberInfo>();
		while(cursor.moveToNext()){
			BlackNumberInfo blackNumberInfo = new BlackNumberInfo();
			blackNumberInfo.phone = cursor.getString(0);
			blackNumberInfo.mode = cursor.getString(1);
			blackNumberList.add(blackNumberInfo);
		}
		cursor.close();
		db.close();
		
		return blackNumberList;
	}
	
	/**
	 * @param phone	作为查询条件的电话号码
	 * @return	传入电话号码的拦截模式	1:短信	2:电话	3:所有	0:没有此条数据
	 */
	public int getMode(String phone){
		SQLiteDatabase db = commSafeOpenHelper.getWritableDatabase();
		int mode = 0;
		Cursor cursor = db.query("blacknumber", new String[]{"mode"}, "phone = ?", new String[]{phone}, null, null,null);
		if(cursor.moveToNext()){
			mode = cursor.getInt(0);
		}
		
		cursor.close();
		db.close();
		return mode;
	}
	 
	
}
